<template>
  <!-- 更新领导带班生产记录 -->
  <base-breadcrumb v-loading="loading.GET_DATA">
    <a-card>
      <title-name title="基本信息" />
      <div class="about-master-container">
        <a-form-model>
          <a-row>
            <a-col span="8">
              <a-form-model-item label="所属分公司" prop="branchComId">
                <a-input v-model="projectInfo.implementationThreeName" disabled />
                <!--<SelectSubCompany v-model="formInfo.branchComId" :disabled="isDisabled" />-->
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="所属项目" prop="projectId">
                <!--<SelectProject
                    v-model="formInfo.projectId"
                    keyValue="branchComId"
                    :form="formInfo"
                    :clear-list="true"
                    :disabled="isDisabled"
                    @change="handleProjectChanged"
                />-->
                <a-input v-model="projectInfo.projectName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="项目地址">
                <BaseInput disabled :value="projectInfo.projectAddress" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="项目经理">
                <BaseInput disabled :value="projectInfo.projectManager && projectInfo.projectManager.name" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="联系电话">
                <BaseInput disabled :value="projectInfo.projectManager && projectInfo.projectManager.phone" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="带班领导">
                <BaseInput disabled :value="formInfo.creatorName" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="职务">
                <BaseInput disabled :value="formInfo.postStrs" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="带班时间">
                <BaseInput disabled :value="formInfo.leadDate" />
              </a-form-model-item>
            </a-col>

            <a-col span="16">
              <a-form-model-item label="形象进度" prop="imageProcessTypeId">
                <a-radio-group v-model="formInfo.imageProcessTypeId" disabled>
                  <a-radio v-for="item in processList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="content">
        <div style="height: 50px;color: black;display:flex;align-items: flex-start;">
          <span style="margin-right: 5px;">一、二级风险详情: </span> <a @click="visible2 = true;params = formInfo">{{ formInfo.majorRiskNum }}个</a>
        </div>
        <div class="item mb30">
          <div class="item-title mb20">
            现场安全生产状况和管理情况：
            <span v-for="item in prodManageList" :key="item.id">
                  <span v-if="item.id == formInfo.prodManageTypeId">{{ item.name }}</span>
                </span>
          </div>
          <BaseTextarea v-if="formInfo.prodManageTypeNote" v-model="formInfo.prodManageTypeNote" placeholder="无"
                        :rows="3" disabled
          />

          <div class="audio" v-if="takeShiftFirstHistoryVO.prodManageTypeMp3FileVO">
            <div class="options" @click="clinckIndex(0)">
              <a-icon type="pause-circle" v-if="amrAudioArr[0].isPlay" />
              <a-icon type="play-circle" v-else />
            </div>
            <div class="duration">
              <!--              <div class="start">00:00</div>-->
              <!--              <div class="progress">-->
              <!--                <div class="point"></div>-->
              <!--                <div class="line"></div>-->
              <!--              </div>-->
              <!--              <div class="end">22:22</div>-->
              <div class="end">{{ amrAudioArr[0].end }}秒</div>
            </div>
          </div>
        </div>
        <div class="item mb30">
          <div class="item-title mb20">下级单位领导带班安全检查制度落实情况</div>
          <span>(1)下级单位领导带班安全检查落实情况：<a @click="visible = true">查看</a></span>
          <div class="mb10 mt10">
            <a-radio-group v-model="takeShiftFirstHistoryVO.securityCheckVo.id" disabled>
              <a-radio :value="item.id" v-for="item in implSituationList" :key="item.id">{{ item.name }}</a-radio>
            </a-radio-group>
          </div>
          <BaseTextarea v-if="formInfo.securityCheckNote" v-model="formInfo.securityCheckNote" placeholder="无" :rows="3"
                        disabled
          />


          <div class="audio" v-if="takeShiftFirstHistoryVO.securityCheckMp3FileVO">
            <div class="options" @click="clinckIndex(1)">
              <a-icon type="pause-circle" v-if="amrAudioArr[1].isPlay" />
              <a-icon type="play-circle" v-else />
            </div>
            <div class="duration">
              <div class="end">{{ amrAudioArr[1].end }}秒</div>
            </div>
          </div>

        </div>
        <div class="item mb30">
              <span>(2)项目经理/执行经理现场带班安全检查制度落实情况：
                <a @click="visible3 = true ">查看</a>
              </span>
          <div class="mb10 mt10">
            <a-radio-group v-model="takeShiftFirstHistoryVO.securityCheckSysVo.id" disabled>
              <a-radio :value="item.id" v-for="item in implSituationList" :key="item.id">{{ item.name }}</a-radio>
            </a-radio-group>
          </div>
          <BaseTextarea v-if="takeShiftFirstHistoryVO.securityCheckSysNote" v-model="takeShiftFirstHistoryVO.securityCheckSysNote" placeholder="无"
                        :rows="3" disabled
          />

          <div class="audio" v-if="takeShiftFirstHistoryVO.securityCheckSysMp3FileVO">
            <div class="options" @click="clinckIndex(2)">
              <a-icon type="pause-circle" v-if="amrAudioArr[2].isPlay" />
              <a-icon type="play-circle" v-else />
            </div>
            <div class="duration">
              <div class="end">{{ amrAudioArr[2].end }}秒</div>
            </div>
          </div>
        </div>
        <div class="item mb30">
          <div class="mb10">下一步安全生产工作要求：</div>
          <BaseTextarea v-if="formInfo.nextWorkReq" v-model="formInfo.nextWorkReq" placeholder="无" :rows="3" disabled />

          <div class="audio" v-if="takeShiftFirstHistoryVO.nextWorkReqMp3FileVO">
            <div class="options" @click="clinckIndex(3)">
              <a-icon type="pause-circle" v-if="amrAudioArr[3].isPlay" />
              <a-icon type="play-circle" v-else />
            </div>
            <div class="duration">
              <div class="end">{{ amrAudioArr[3].end }}秒</div>
            </div>
          </div>
        </div>
        <div class="item" style="display:flex;">
          <span class="mr10">照片：</span>
          <upload-list
            :businessCode="'SHE03'"
            :editModel="0"
            :uploadArrys.sync="takeShiftFirstHistoryVO.fileArrays"
            uploadType="image"
            multiple
            :isMultiple="true"
          />
        </div>
      </div>
    </a-card>

    <a-card v-if="isShowReply">
      <title-name title="整改落实情况" />
      <div class="about-master-container">
        <a-form-model ref="form" :model="formInfo" :rules="rules">
          <a-form-model-item label="指派" prop="replyUserId" v-if="isShowReplyUser">
            <ASelectOrgPeople
              style="width: 300px;"
              :disabled="isDisabled"
              @onSelectChange="getPeople"
              :selectPeopleName="formInfo.replyUserName"
              :form="formInfo"
              :init="false"
              key-value="projectDeptOrgId"
              v-model="formInfo.replyUserId"
            />
          </a-form-model-item>
           <!-- 指派人回复和选中自己 -->
          <template v-if="isShowReplyOther || (formInfo.replyStatusStr === '待回复' && formInfo.pmStatus*1===1) || formInfo.replyUserId == capyReplyUserId">
            <a-form-model-item label="项目回复" prop="managerReply">
              <BaseTextarea v-model="formInfo.managerReply" :rows="3" :disabled="isDisabled" />
            </a-form-model-item>
            <a-form-model-item label="照片" prop="replyFileList">
              <upload-list
                :disabled="isDisabled"
                :businessCode="'SHE03'"
                :editModel="1"
                :uploadArrys.sync="formInfo.replyFileList"
                uploadType="image"
                multiple
                :isMultiple="true"
              ></upload-list>
            </a-form-model-item>
          </template>
        </a-form-model>
      </div>
    </a-card>
    <div class="tool-btns page-btn-right-top">
      <!--      <BasePrintButton type="primary" :beforePrintFn="print" />-->
      <a-button v-if="pageType === 'edit'" type="primary" :loading="loading.GET_DATA" @click="handleSave()">
        提交
      </a-button>
      <a-button class="ml20" @click="$close">关闭</a-button>
    </div>
    <sign-modal :type="type" :visible.sync="visible" :initData="initData"></sign-modal>
    <sign-modal2 :visible.sync="visible3" :initData="initData"></sign-modal2>
    <RiskDetail :visible.sync="visible2" :params="params" />
  </base-breadcrumb>
</template>

<script>
import { getProjectsDel } from '@/api/project/projects'
import SelectSubCompany from '@/components/Select/SelectSubCompany.vue'
import SelectProject from '@/components/Select/SelectProject.vue'
import UploadList from '@/components/UploadList'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import {
  getProductionRecordDetail,
  getProductionRecordDetailPrint,
  updateProductionRecord, pmReplay, replyUser
} from '@/api/safetySupervision/safetySystem.js'
import { getSelectListByType } from '@/api/safetySupervision/common.js'
import { getInfoByStaffId } from '@/api/commons'
import signModal from './SignModal'
import signModal2 from './SignModal2'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import Vue from 'vue'
import RiskDetail from '@/views/safetySupervision/leaderProductionRecord/productionRecordList/RiskDetail' // 版本详情
import BenzAMRRecorder from 'benz-amr-recorder'

export default {
  name: 'a' + Date.now(),
  components: {
    UploadList,
    SelectSubCompany,
    SelectProject,
    signModal,
    signModal2,
    BasePrintButton,
    ASelectOrgPeople,
    RiskDetail
  },
  data() {
    return {
      implSituationList: [], // 落实情况 type:7
      prodManageList: [], // 现场生产、管理情况 type:5
      processList: [], // 形象进度 type:6
      projectInfo: { projectManager: { posts: [], name: '' } }, // 工程项目相关信息
      loading: {
        GET_DATA: false,
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false
      },
      type: '1', //1领导带班 2项目经理带班
      visible: false,
      visible3: false,
      visible2: false,
      params:{},
      initData: {},
      formInfo: {
        status: 'DRAFT',
        branchComId: '',
        projectId: '',
        projectDeptOrgId: '',
        fileList: [],
        replyFileList: [],
        imageProcessTypeId: '',
        majorRiskProject: '',
        nextWorkReq: '',
        prodManageTypeId: '',
        securityCheckId: '',
        securityCheckSysId: '',
        replyUserId: undefined,
        capyReplyUserId:null, 
      },
      rules: {
        branchComId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
        imageProcessTypeId: [{ required: true, message: '请选择形象进度', trigger: 'change' }],
        majorRiskProject: [{ required: true, message: '请输入', trigger: 'change' }],
        nextWorkReq: [{ required: true, message: '请输入', trigger: 'change' }],
        prodManageTypeId: [{ required: true, message: '请选择', trigger: 'change' }],
        securityCheckId: [{ required: true, message: '请选择', trigger: 'change' }],
        securityCheckSysId: [{ required: true, message: '请选择', trigger: 'change' }],
        managerReply: [{ required: true, message: '请输入项目回复', trigger: 'change' }],
        replyFileList: [{ required: true, message: '请上传照片', trigger: 'change' }]
      },
      token: '',
      amrAudioArr:[{isPlay: false,player: null,start: 0,end: 0},{isPlay: false,player: null,start: 0,end: 0},{isPlay: false,player: null,start: 0,end: 0},{isPlay: false,player: null,start: 0,end: 0}],
      takeShiftFirstHistoryVO:{
        securityCheckVo:{
          id:null,
        },
        securityCheckSysVo:{
          id:null,
        }
      },  //历史数据
    }
  },
  computed: {
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    isShowReply() {
      if (this.isDisabled) {
        return this.formInfo.replyStatus === 2
      }
      return true
    },
    isShowReplyOther() {
      if (this.isDisabled) {
        return true
      }
      return !this.formInfo.replyUserId
    },
    isShowReplyUser() {
      if (this.isDisabled) {
        return false
      }
      return this.formInfo.pmStatus === 0
      // if (this.formInfo.replyUserId) {
      //   return true
      // } else {
      //   if (this.isDisabled) {
      //     return false
      //   }
      //   return this.formInfo.pmStatus === 0
      // }
    },
    getPost() {
      return this.projectInfo?.projectManager?.posts?.map(v => v.name).join('、')
    }
  },
  created() {
    this.token = Vue.getAcloudProvider().getAccessToken()

    if (this.$route.query.id) {
      this.formInfo.id = this.$route.query.id
      this.getDetail()
    }
    this.getAllSelectList()
  },
   watch:{
    $route:{
      handler(val,oldval){
        this.closeAudio();
      },
      // 深度观察监听
      deep: true
    }
  },
  methods: {
    closeAudio(){
          this.amrAudioArr.length && this.amrAudioArr.map((item,arrIndex)=>{
          item.player && item.player.stop()
       })
    },
   clinckIndex(index){
     this.amrAudioArr.map((item,arrIndex)=>{
        if(arrIndex === index){
          if(item.isPlay){
              item.player && item.player.stop()
          }else{
            item.player && item.player.play();
          }
        }else{
          item.isPlay = false;
         item.player && item.player.stop()
        }
      })
   }, 
    getMp3(file) {
      // return 'http://localhost:8000/api/ycloud-file-center/oper/download?access_token=7365a71b2518fa6f0f7dc07e1abea4d5&fileId=16388959018E9F300CBFE303172B9C01&fullfilename=16388959018E9F300CBFE303172B9C01.mp3'
      if (!file) return
      return window.location.origin + '/api/ycloud-file-center/oper/download?access_token=' + this.token + '&fileId=' + file.fileId + '&fullfilename=' + file.alias
    },
    async getPeople(e) {
      this.formInfo.replyUserName = e.name
    },
    print() {
      return getProductionRecordDetailPrint({ id: this.formInfo.id }).then((res) => {
        return res[1].data.content
      })
    },
    handerPage() {
      this.$router.push({
        name: 'UpdateProjectControl',
        query: {
          pageType: 'look',
          id: this.formInfo.criticalProjectId || ''
        }
      })
    },
    // 获取下拉列表数据
    getAllSelectList() {
      const loopList = [
        { name: 'processList', type: 6 },
        { name: 'prodManageList', type: 5 },
        { name: 'implSituationList', type: 7 }
      ]
      loopList.forEach((item) => {
        this.getSelectList(item.type, item.name)
      })
    },
    async getSelectList(type, name) {
      const [err, res] = await getSelectListByType({ type })
      if (!err) {
        this[name] = res.data || []
      }
    },
    filterEditModel(type) {
      let flag = ''
      switch (type) {
        case 'add':
          flag = 2
          break
        case 'edit':
          flag = 1
          break
        case 'look':
          flag = 0
          break
        default:
          flag = 0
          break
      }
      return flag
    },
    async getDetail() {
      this.loading.GET_DATA = true
      const [err, res] = await getProductionRecordDetail({ id: this.formInfo.id })
      if (!err) {
        // if (res.data.pmStatus === 0) {
        //   if (res.data.replyUserId === this.$userInfo().id) {
        //     res.data.replyUserId = ''
        //     res.data.replyUserName = ''
        //   }
        // }
        this.formInfo = { ...this.formInfo, ...res.data }
        this.takeShiftFirstHistoryVO = res.data.takeShiftFirstHistoryVO || {};
        if(!this.takeShiftFirstHistoryVO.securityCheckVo){
         this.takeShiftFirstHistoryVO.securityCheckVo = {id:null}
        }
        if(!this.takeShiftFirstHistoryVO.securityCheckSysVo){
         this.takeShiftFirstHistoryVO.securityCheckSysVo = {id:null}
        }
        console.log( this.takeShiftFirstHistoryVO,' this.takeShiftFirstHistoryVO =')
        this.capyReplyUserId = this.formInfo.replyUserId?JSON.parse(JSON.stringify(this.formInfo.replyUserId)):null;
        await this.handleProjectChanged(this.formInfo.projectId)

        if (this.takeShiftFirstHistoryVO.prodManageTypeMp3FileVO) {
          await this.initAudio(this.amrAudioArr[0], this.takeShiftFirstHistoryVO.prodManageTypeMp3FileVO)
        }
        if (this.takeShiftFirstHistoryVO.securityCheckMp3FileVO) {
          await this.initAudio(this.amrAudioArr[1], this.takeShiftFirstHistoryVO.securityCheckMp3FileVO)
        }
        if (this.takeShiftFirstHistoryVO.securityCheckSysMp3FileVO) {
          await this.initAudio(this.amrAudioArr[2], this.takeShiftFirstHistoryVO.securityCheckSysMp3FileVO)
        }
        if (this.takeShiftFirstHistoryVO.nextWorkReqMp3FileVO) {
          await this.initAudio(this.amrAudioArr[3], this.takeShiftFirstHistoryVO.nextWorkReqMp3FileVO)
        }
      }
      this.loading.GET_DATA = false
    },
    async initAudio(audio, file) {
      let src = this.getMp3(file)
      audio.player = new BenzAMRRecorder()
      await audio.player.initWithUrl(src)
      audio.end = audio.player.getDuration()
      audio.player.onEnded(() => {
        audio.isPlay = false
      })
      audio.player.onPause(() => {
        audio.isPlay = false
      })
      audio.player.onPlay(() => {
        audio.isPlay = true
      })
      audio.player.onResume(() => {
        audio.isPlay = true
      })
    },
    async handleProjectChanged(id) {
      if (!id) return this.projectInfo = {}
      const res = await getProjectsDel({ projectId: id }) // 获取项目详情信息
      this.initData = this.projectInfo = res.data || {}
      this.formInfo.projectDeptOrgId = res.data.projectDeptOrgId
      if (res.data.realityPmId) {
        const employee = await getInfoByStaffId(res.data.realityPmId)
        if (employee.data) {
          this.projectInfo.projectManager = employee.data
        }
      }
    },

    async handleSave() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading.GET_DATA = true
          const params = { ...this.formInfo }
          let flag = null;
          //指派人不是自己或指派人为空
          if(this.formInfo.pmStatus == 0 && this.formInfo.replyUserId !== this.capyReplyUserId && this.formInfo.replyUserId){
            flag = true;
          }else{
            flag = false
          }
          const fn = flag ? replyUser : pmReplay
          const [err, res] = await fn(params)
          this.loading.GET_DATA = false
          if (!err) {
            this.$message.success('成功')
            this.$close()
          }
        } else {
          this.$noticeWarning('请填写完整')
        }
      })
    }
  },
  destroyed(){
     this.closeAudio();
  },
}
</script>

<style lang="less" scoped>
.content {
  padding-left: 50px;

  .item {
    .item-title {
      font-size: 16px;
      font-weight: bold;
      margin-top: 10px;
    }

    .audio {
      margin-top: 15px;
      margin-bottom: 15px;
      width: 200px;
      display: flex;
      padding: 0 30px;
      border-radius: 30px;
      border: 1px solid #d9d9d9;
      background: #f5f5f5;

      .options {
        font-size: 22px;
      }

      .duration {
        margin-left: 20px;
        display: flex;
        align-items: center;
        flex: 1;
      }

      .progress {
        margin: 0 .6rem;
        flex: 1;
        position: relative;
        display: flex;
        align-items: center;

        //.slide-bar {
        //  position: absolute;
        //  height: 2rem;
        //  width: 100%;
        //  top: -1rem;
        //  z-index: 9;
        //}

        &:before {
          z-index: 8;
          content: ' ';
          height: 3px;
          width: 100%;
          background: white;
          position: absolute;
        }

        .line {
          z-index: 9;
          content: '';
          position: absolute;
          height: 3px;
          width: 100%;
          background: rgb(2, 167, 240);
        }

        .point {
          z-index: 9;
          position: absolute;
          left: 0;
          //top: -3px;
          height: 8px;
          width: 8px;
          border-radius: 50%;
          background: rgb(2, 167, 240);
        }
      }

    }
  }
}

.mb30 {
  margin-bottom: 30px;
}
</style>